package com.invengo.module_check.ui.fragment.first_check;

import android.app.Application;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableBoolean;
import androidx.databinding.ObservableField;

import com.invengo.library_db.entity.module_check.ShelfBean;
import com.invengo.library_rfid.classify.AnalyzeImpl;
import com.invengo.library_rfid.classify.RFIDCallBackListener;
import com.invengo.library_rfid.entity.TagInfo;
import com.invengo.module_check.data.repsitory.business.BusinessRepsitory;

import java.util.List;

import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.goldze.mvvmhabit.utils.cache.ACache;
import me.goldze.mvvmhabit.utils.cache.AKey;

public class FirstSelectShelfViewModel extends BaseViewModel<BusinessRepsitory> {
    public ObservableBoolean isFirst = new ObservableBoolean(true);
    public ObservableField<String> firstShelfCode = new ObservableField<>();
    public ObservableField<String> firstShelfName = new ObservableField<>();

    public ObservableField<String> secondShelfName = new ObservableField<>();
    public ObservableField<String> secondShelfCode = new ObservableField<>();
    public ObservableBoolean openSelectShelf = new ObservableBoolean(ACache.getInstance().getAsBoolean(AKey.IS_OPEN_SELECT_SHELF));//是否开启层架选择

    public FirstSelectShelfViewModel(@NonNull Application application) {
        super(application, BusinessRepsitory.getInstance());
        registerRFID(new RFIDCallBackListener(AnalyzeImpl.TO_SHELF, tagInfo -> onScanResult(tagInfo), state -> isReading.set(state)));
    }

    public UIChangeObservable ui = new UIChangeObservable();

    public class UIChangeObservable {
        public SingleLiveEvent<List<ShelfBean>> nextEvent = new SingleLiveEvent<>();
        public SingleLiveEvent<Boolean> multiChangeEvent = new SingleLiveEvent<>();
        public SingleLiveEvent<ShelfBean> selectShelfEvent = new SingleLiveEvent<>();
    }

    public void onScanResult(TagInfo tagInfo) {
        switch (tagInfo.getRfidModel()) {
            case TID:
                if (tagInfo.getScanModel() == AnalyzeImpl.TO_SHELF)
                    getShelfByTid(tagInfo.getTag());
                else {
//                    getBookByTid(tagInfo.getTag());
                }
                break;
            case EPC:
            case U_DATA:
                if (tagInfo.getScanModel() == AnalyzeImpl.TO_SHELF)
                    getShelfByCode(tagInfo.getTag());
                else {
//                    getBookByCode(tagInfo.getTag());
                }
                break;
        }
    }

    /**
     * 按tid取架
     *
     * @param tid 时间
     */
    private void getShelfByTid(String tid) {
        model.getShelfInfoByTid(tid)
                .compose(RxUtils.applySchedulersToast(getLifecycleProvider(), this))
                .subscribe(bean -> {
                    handlerShelf(bean);
                });
    }

    /**
     * 查询货架信息
     *
     * @param shelfCode 标签
     */
    private void getShelfByCode(String shelfCode) {
        model.getShelfInfoByCode(shelfCode)
                .compose(RxUtils.applySchedulersToast(getLifecycleProvider(), this))
                .subscribe(bean -> {
                    handlerShelf(bean);
                });
    }

    public void handlerShelf(ShelfBean bean) {
        getUC().getHideKeyboardEvent().call();
        if (isFirst.get()) {
            firstShelfCode.set(bean.getShelfCode());
            firstShelfName.set(bean.getShelfName());
            changeForce(false);
        } else {
            secondShelfCode.set(bean.getShelfCode());
            secondShelfName.set(bean.getShelfName());
        }
//        KLog.e("---------------------"+(!StringUtils.isEmpty(firstShelfCode.get()) && !StringUtils.isEmpty(secondShelfCode.get())));
        if (!StringUtils.isEmpty(firstShelfCode.get()) && !StringUtils.isEmpty(secondShelfCode.get())) {
            if (TextUtils.isEmpty(firstShelfCode.get()) | TextUtils.isEmpty(secondShelfCode.get())) {
                ToastUtils.showShort("请先扫描层位标签或输入层位代码");
                return;
            }
            int compareResult = firstShelfCode.get().compareTo(secondShelfCode.get());
            if (compareResult >= 0) {
                ToastUtils.showShort("起始层位不能大于或等于截止层位");
                secondShelfCode.set("");
                secondShelfName.set("");
                return;
            }

        }
    }

    private void getErrorShelfList() {
        model.getErrorShelf(firstShelfCode.get(), secondShelfCode.get())
                .compose(RxUtils.applySchedulersLoading(getLifecycleProvider(), this))
                .subscribe(shelfBeans -> {
                    if (shelfBeans.isEmpty()) {
                        ToastUtils.showShort("该区间内无错误首书");
                    } else {
                        ui.nextEvent.postValue(shelfBeans);
                    }
                });
    }


    public BindingCommand move2First = new BindingCommand<>(() -> {
        KLog.e("移动第11111");
        isFirst.set(true);
    });
    public BindingCommand move2Secound = new BindingCommand<>(() -> {
        KLog.e("移动第二222");
        isFirst.set(false);
    });
    public void changeForce(Boolean b) {
        ui.multiChangeEvent.postValue(b);
    }

    public BindingCommand<String> byShelfChange = new BindingCommand<>(s -> {
        if (isFirst.get()) {
            if (!firstShelfCode.equals(s)) {
                getShelfByCode(s);
            }
        } else {
            if (!secondShelfCode.equals(s)) {
                getShelfByCode(s);
            }
        }
    });
    /**
     * 清除所有数据
     */
    public BindingCommand cleanAllData = new BindingCommand(() -> {
        cleanRFIDCacheNotStop();
        firstShelfName.set("");
        firstShelfCode.set("");
        secondShelfName.set("");
        secondShelfCode.set("");
        isFirst.set(true);
    });
    /**
     * 开始检查
     */
    public BindingCommand startCheck = new BindingCommand(() -> {
//        getShelfList(firstShelfCode.get());
        getErrorShelfList();
    });

    public void shelectShelf(boolean isFirst) {
        ShelfBean bean = null;
        String name = isFirst ? firstShelfName.get() : secondShelfName.get();
        String code = isFirst ? firstShelfCode.get() : secondShelfCode.get();
        if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(code)) {
            bean = new ShelfBean();
            bean.setShelfName(name);
            bean.setShelfCode(code);
        }
        ui.multiChangeEvent.postValue(isFirst);
        ui.selectShelfEvent.postValue(bean);
    }
}
